// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database();
  const _ = db.command;
  var user = {};
  console.log('event==', event)
  console.log('wxContext==', wxContext)
  try {
    user = (await db.collection('cuser').doc(event.userInfo.openId).get()).data;
    if (event.studioid) {

      if (!user.studioList) user.studioList = [];
      let index = user.studioList.indexOf(event.studioid);
      while (index >= 0) {
        user.studioList.splice(index, 1);
        index = user.studioList.indexOf(event.studioid);
      }
      user.studioList.unshift(event.studioid);

      await db.collection('cuser').doc(event.userInfo.openId).update({
        data: {
          studioList: user.studioList
        }
      });
      user.studioid = event.studioid;

    } else {
      if (Array.isArray(user.studioList) && user.studioid.length > 0) {
        user.studioid = user.studioList[0];
      }
    }
  } catch (e) {
    user = {
      openid: event.userInfo.openId,
      appid: event.userInfo.appId,
      studioid: event.studioid,
      studioList: [event.studioid]
    }
  }

  let studio = {};
  if (user.studioid) {
    try {
      await db.collection('studio').doc(user.studioid).update({
        data: {
          visit: _.inc(1)
        }
      });
      studio = (await db.collection('studio').where({
        _id: event.studioid,
        appid: event.userInfo.appId
      }).get()).data[0];

      user.studios = [];
      if (user.studioList.length > 1) {
        console.log(user.studioList.slice(1));
        let studios = (await db.collection('studio').where({
          _id: _.in(user.studioList.slice(1))
        }).field({
          title: true,
          'logo.src': true,
          'location.name': true,
          appid: true,
          serviceType: true,
        }).get()).data;
        if (studios.length > 0)
          user.studios = user.studios.concat(studios);
      }
    } catch (e) {

    }
  }
  // if (Array.isArray(studio.cover)) {
  //   studio.cover.map(v => {
  //     v.src = v.src.replace(/\/mini$/i, '');
  //   })
  // }
  console.log(user, studio);
  return {
    user,
    studio
  };

}